import React from 'react';
import { Clock, Play, Pause, CheckCircle, XCircle, AlertCircle } from 'lucide-react';
import { ProcessTask, TaskStatus } from '@/types/video';

interface BatchProgressProps {
  tasks: ProcessTask[];
  currentTask: ProcessTask | null;
  isProcessing: boolean;
  className?: string;
}

export const BatchProgress: React.FC<BatchProgressProps> = ({
  tasks,
  currentTask,
  className = '',
}) => {
  const getStatusIcon = (status: TaskStatus) => {
    switch (status) {
      case 'completed':
        return <CheckCircle className='w-4 h-4 text-green-500' />;
      case 'failed':
        return <XCircle className='w-4 h-4 text-red-500' />;
      case 'processing':
        return <Play className='w-4 h-4 text-blue-500 animate-pulse' />;
      case 'paused':
        return <Pause className='w-4 h-4 text-yellow-500' />;
      case 'canceled':
        return <XCircle className='w-4 h-4 text-gray-500' />;
      default:
        return <AlertCircle className='w-4 h-4 text-gray-400' />;
    }
  };

  const getStatusColor = (status: TaskStatus) => {
    switch (status) {
      case 'completed':
        return 'text-green-600 bg-green-50 border-green-200';
      case 'failed':
        return 'text-red-600 bg-red-50 border-red-200';
      case 'processing':
        return 'text-blue-600 bg-blue-50 border-blue-200';
      case 'paused':
        return 'text-yellow-600 bg-yellow-50 border-yellow-200';
      case 'canceled':
        return 'text-gray-600 bg-gray-50 border-gray-200';
      default:
        return 'text-gray-600 bg-gray-50 border-gray-200';
    }
  };

  const formatTime = (seconds: number): string => {
    if (seconds < 60) {
      return `${Math.round(seconds)}秒`;
    } else if (seconds < 3600) {
      return `${Math.floor(seconds / 60)}分${Math.round(seconds % 60)}秒`;
    } else {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      return `${hours}时${minutes}分`;
    }
  };

  const formatProgress = (task: ProcessTask): string => {
    if (task.status === 'completed') {
      return '完成';
    }
    if (task.status === 'failed') {
      return '失败';
    }
    if (task.status === 'canceled') {
      return '已取消';
    }
    if (task.status === 'paused') {
      return '已暂停';
    }

    return `${task.progress.percentage}% - ${task.progress.currentPhase}`;
  };

  const calculateOverallProgress = (): number => {
    if (tasks.length === 0) return 0;

    const totalProgress = tasks.reduce((sum, task) => {
      return sum + task.progress.percentage;
    }, 0);

    return Math.round(totalProgress / tasks.length);
  };

  const completedTasks = tasks.filter(t => t.status === 'completed').length;
  const failedTasks = tasks.filter(t => t.status === 'failed').length;
  const activeTasks = tasks.filter(t => t.status === 'processing' || t.status === 'paused').length;
  const pendingTasks = tasks.filter(t => t.status === 'pending').length;

  const overallProgress = calculateOverallProgress();

  return (
    <div className={`space-y-4 ${className}`}>
      {/* 总体进度 */}
      <div className='card p-4'>
        <div className='flex items-center justify-between mb-4'>
          <div className='flex items-center space-x-2'>
            <Clock className='w-5 h-5 text-gray-500' />
            <h4 className='text-lg font-semibold text-gray-900'>总体进度</h4>
          </div>

          <div className='text-right'>
            <div className='text-2xl font-bold text-blue-600'>{overallProgress}%</div>
            <div className='text-sm text-gray-600'>
              {completedTasks}/{tasks.length} 完成
            </div>
          </div>
        </div>

        {/* 进度条 */}
        <div className='space-y-2'>
          <div className='w-full bg-gray-200 rounded-full h-3'>
            <div
              className='bg-blue-600 h-3 rounded-full transition-all duration-300'
              style={{ width: `${overallProgress}%` }}
            />
          </div>

          <div className='flex justify-between text-sm text-gray-600'>
            <span>总体进度</span>
            <span>{overallProgress}%</span>
          </div>
        </div>

        {/* 统计信息 */}
        <div className='grid grid-cols-4 gap-4 mt-4 pt-4 border-t border-gray-200'>
          <div className='text-center'>
            <div className='text-2xl font-bold text-green-600'>{completedTasks}</div>
            <div className='text-xs text-gray-600'>已完成</div>
          </div>
          <div className='text-center'>
            <div className='text-2xl font-bold text-blue-600'>{activeTasks}</div>
            <div className='text-xs text-gray-600'>进行中</div>
          </div>
          <div className='text-center'>
            <div className='text-2xl font-bold text-yellow-600'>{pendingTasks}</div>
            <div className='text-xs text-gray-600'>等待中</div>
          </div>
          <div className='text-center'>
            <div className='text-2xl font-bold text-red-600'>{failedTasks}</div>
            <div className='text-xs text-gray-600'>失败</div>
          </div>
        </div>
      </div>

      {/* 当前任务详情 */}
      {currentTask && (
        <div className='card p-4'>
          <h4 className='text-lg font-semibold text-gray-900 mb-3'>当前处理任务</h4>

          <div className='space-y-3'>
            <div className='flex items-center justify-between'>
              <span className='text-sm font-medium text-gray-700'>文件名</span>
              <span className='text-sm text-gray-900 truncate max-w-xs'>
                {currentTask.inputFiles[0].name}
              </span>
            </div>

            <div className='flex items-center justify-between'>
              <span className='text-sm font-medium text-gray-700'>状态</span>
              <div
                className={`flex items-center space-x-1 px-2 py-1 rounded-full text-xs border ${getStatusColor(currentTask.status)}`}
              >
                {getStatusIcon(currentTask.status)}
                <span>{currentTask.status}</span>
              </div>
            </div>

            <div className='flex items-center justify-between'>
              <span className='text-sm font-medium text-gray-700'>进度</span>
              <span className='text-sm text-gray-900'>{formatProgress(currentTask)}</span>
            </div>

            <div className='flex items-center justify-between'>
              <span className='text-sm font-medium text-gray-700'>已用时间</span>
              <span className='text-sm text-gray-900'>
                {formatTime(currentTask.progress.timeElapsed)}
              </span>
            </div>

            {currentTask.progress.timeRemaining > 0 && (
              <div className='flex items-center justify-between'>
                <span className='text-sm font-medium text-gray-700'>预计剩余时间</span>
                <span className='text-sm text-gray-900'>
                  {formatTime(currentTask.progress.timeRemaining)}
                </span>
              </div>
            )}
          </div>

          {/* 当前任务进度条 */}
          <div className='mt-4 space-y-2'>
            <div className='w-full bg-gray-200 rounded-full h-2'>
              <div
                className='bg-blue-600 h-2 rounded-full transition-all duration-300'
                style={{ width: `${currentTask.progress.percentage}%` }}
              />
            </div>
            <div className='flex justify-between text-xs text-gray-600'>
              <span>{currentTask.progress.currentPhase}</span>
              <span>{currentTask.progress.percentage}%</span>
            </div>
          </div>
        </div>
      )}

      {/* 任务列表 */}
      <div className='card p-4'>
        <h4 className='text-lg font-semibold text-gray-900 mb-3'>任务列表</h4>

        <div className='space-y-2 max-h-60 overflow-y-auto'>
          {tasks.map(task => (
            <div
              key={task.id}
              className={`flex items-center justify-between p-3 rounded-lg border transition-colors ${
                task.id === currentTask?.id
                  ? 'border-blue-300 bg-blue-50'
                  : 'border-gray-200 hover:bg-gray-50'
              }`}
            >
              <div className='flex items-center space-x-3 flex-1 min-w-0'>
                {getStatusIcon(task.status)}

                <div className='flex-1 min-w-0'>
                  <div className='flex items-center space-x-2'>
                    <span className='text-sm font-medium text-gray-900 truncate'>
                      {task.inputFiles[0].name}
                    </span>

                    {task.id === currentTask?.id && (
                      <span className='px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded-full'>
                        当前任务
                      </span>
                    )}
                  </div>

                  <div className='flex items-center space-x-4 text-xs text-gray-600 mt-1'>
                    <span>{formatProgress(task)}</span>
                    <span>已用: {formatTime(task.progress.timeElapsed)}</span>
                    {task.progress.timeRemaining > 0 && (
                      <span>剩余: {formatTime(task.progress.timeRemaining)}</span>
                    )}
                  </div>
                </div>
              </div>

              <div className='flex items-center space-x-2'>
                <div className='text-right text-sm text-gray-600'>{task.progress.percentage}%</div>

                {/* 任务进度条 */}
                <div className='w-20 bg-gray-200 rounded-full h-2'>
                  <div
                    className={`h-2 rounded-full transition-all duration-300 ${
                      task.status === 'completed'
                        ? 'bg-green-500'
                        : task.status === 'failed'
                          ? 'bg-red-500'
                          : task.status === 'processing'
                            ? 'bg-blue-500'
                            : 'bg-gray-400'
                    }`}
                    style={{ width: `${task.progress.percentage}%` }}
                  />
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default BatchProgress;
